package top.rainf.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.rainf.service.IEmailService;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author 星环
 * @date 2023/5/8 10:21:11
 * @description
 */
@Slf4j
@Service
public class EmailService implements IEmailService {
    @Override
    public void sendEmail(String toEmail,String subject,String content) {
        MimeMessage mail = createMail(toEmail, subject,content);
        log.info("正在发送邮件...");
        try {
            Transport.send(mail);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        log.info("给{}发送了一封邮件，标题是:{}",toEmail,subject);
    }

    /**
     * 实际创建邮件的方法
     * @param toEmail 发送到 谁的邮箱
     * @param subject 发送邮件的主题
     * @param content 发送的内容
     * @return 生成好的邮件
     */
    private MimeMessage createMail(String toEmail, String subject, String content) {
        MimeMessage msg = null;
        try {
            Session session = createSession();
            msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("403345548@qq.com"));
            msg.setRecipient(Message.RecipientType.TO,new InternetAddress(toEmail));
            msg.setSubject(subject);
            msg.setText(content);

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        return msg;
    }

    /**
     * 创建Session，一次smtp邮件对话
     * @return 创建的session
     */
    private static Session createSession(){
        String smtp = "smtp.qq.com";
        String username = "403345548@qq.com";
        String pwd = "wdhgjlhgycyubidg";
        Properties props = new Properties();
        props.put("mail.smtp.host",smtp);
        props.put("mail.smtp.port",25);
        props.put("mail.smtp.auth","true");
        props.put("mail.smtp.starttls.enable","true");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username,pwd);
            }
        });
        return session;
    }
}
